import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Col, DatePicker, Form, Input, Row, Select, Spin, message } from 'antd';
import { Ref, useContext, useEffect, useRef, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
import { getCompanyName, getKeyRouter, getLoadMapList, getPosName, getTenantID, getUserDepName, getUserName, onCloseModalCommon } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew } from '@/components/TagSelectNew';
import { UploadFormCommon } from '@/components/UploadForm';
import moment from 'moment';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import { addQualifyService, editQualifyService, getQualifyByIdService } from '../services';
const TodayDatePicker: any = DatePicker;

export const QualifyUpdateModal: React.FC<SupplierManageAPI.IQualifyUpdateModal> = ({ onClose, qualifiCheckRows, reloadQualifyManage }) => {
  /** 获取上下文 */
  const { locationID, qualifyDataList, supplierDispath } = useContext(SupplierLocaldataContext);

  /** 表单 */
  const [qulificationForm] = Form.useForm();

  /** 弹框Ref */
  const qulificationModalRef: Ref<IOneModalRef> = useRef(null);

  /** 存储是否选择永久有效期 */
  const [isExpireEndTime, setIsExpireEndTime] = useState<number>(1);

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.QUALIFICA_TYPE}`, //企业资质类型
  ]);

  /**
   * 详情接口回调
   * @param res
   */
  const getQualifyByIdCallback = (res: any) => {
    if (res && res?.msgFlag) {
      qulificationForm?.setFieldsValue({
        ...res?.obj,
        expireBegin: res?.obj?.expireBegin ? moment(res?.obj?.expireBegin) : null,
        expireFinish: res?.obj?.expireFinish ? moment(res?.obj?.expireFinish) : null,
      });
      setIsExpireEndTime(res?.obj?.isExpire);
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情接口 */
  const { getQualifyByIdInfo, getQualifyByIdLoading, getQualifyByIdRun } = getQualifyByIdService(getQualifyByIdCallback);

  /** 添加编辑接口回调 */
  const updateCalblack = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadQualifyManage();
      onCloseModalCommon(qulificationModalRef);
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入添加接口 */
  const { addQualifyLoading, addQualifyRun } = addQualifyService(updateCalblack);

  /** 引入编辑接口 */
  const { editQualifyLoading, editQualifyRun } = editQualifyService(updateCalblack);

  /** 初始化 */
  useEffect(() => {
    if (qualifiCheckRows && qualifiCheckRows?.key) {
      qulificationForm?.setFieldsValue({
        ...qualifiCheckRows,
        expireBegin: qualifiCheckRows?.expireBegin ? moment(qualifiCheckRows?.expireBegin) : null,
        expireFinish: qualifiCheckRows?.expireFinish ? moment(qualifiCheckRows?.expireFinish) : null,
      });
      setIsExpireEndTime(qualifiCheckRows?.isExpire);
    } else if (qualifiCheckRows && qualifiCheckRows?.id) {
      getQualifyByIdRun({ id: qualifiCheckRows?.id }); //模拟数据-王志龙

      // qulificationForm?.setFieldsValue({
      //   //模拟数据-王志龙
      //   ...qualifiCheckRows,
      //   expireBegin: qualifiCheckRows?.expireBegin ? moment(qualifiCheckRows?.expireBegin) : null,
      //   expireFinish: qualifiCheckRows?.expireFinish ? moment(qualifiCheckRows?.expireFinish) : null,
      // });
      setIsExpireEndTime(qualifiCheckRows?.isExpire);
    }
  }, [qualifiCheckRows]);

  /** 保存资质信息 */
  const onSaveQulifica = () => {
    qulificationForm?.validateFields()?.then((values: any) => {
      const attachTypeObj: Record<string, any> = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.QUALIFICA_TYPE}`]?.find(
        (item: any) => item?.id == values?.attachType,
      );
      let payload: Record<string, any> = {
        ...values,
        expireBegin: values?.expireBegin ? moment(values?.expireBegin).format('YYYY-MM-DD HH:mm:ss') : null,
        expireFinish: values?.expireFinish ? moment(values?.expireFinish).format('YYYY-MM-DD HH:mm:ss') : null,
        attachTypeName: `${attachTypeObj?.name}||${attachTypeObj?.fontColor}`,
      };
      if (locationID) {
        /** 编辑供应商逻辑 */
        if (getQualifyByIdInfo && getQualifyByIdInfo?.id) {
          const editPayload: Record<string, any> = {
            ...payload,
            id: getQualifyByIdInfo?.id,
            versionNum: getQualifyByIdInfo?.versionNum,
            supplierID: locationID,
          };
          editQualifyRun(editPayload);
        } else {
          payload['supplierID'] = locationID;
          addQualifyRun(payload);
        }
      } else {
        let newQulifiList: Record<string, any>[] = [...qualifyDataList];
        /** 添加供应商逻辑 */
        if (qualifiCheckRows && qualifiCheckRows?.key) {
          /** 编辑资质逻辑 */
          newQulifiList = newQulifiList?.filter((item: any) => item?.key != qualifiCheckRows?.key);
          const editQulifiInfo: Record<string, any> = {
            ...qualifiCheckRows,
            ...payload,
          };
          newQulifiList?.push(editQulifiInfo);
        } else {
          const addQulifiInfo: Record<string, any> = {
            ...payload,
            key: `qulificati-${getKeyRouter()}`,
            createrName: getUserName(),
            createPositionName: getPosName(),
            createDepartmentName: getUserDepName(),
            createCompanyName: getCompanyName(),
            createTime: moment()?.format('YYYY-MM-DD HH:mm:ss'),
          };
          newQulifiList?.push(addQulifiInfo);
        }

        supplierDispath({
          type: ISupplierActionEnum.QUALIFYDATA_LIST,
          payload: newQulifiList,
        });

        onCloseModalCommon(qulificationModalRef);
      }
    });
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={qulificationModalRef}
        title={qualifiCheckRows?.id ? '编辑资质信息' : '添加资质信息'}
        width={document.body.clientWidth * 0.45}
        onCancel={onClose}
        bodyStyle={{
          padding: '5px 10px',
        }}
        onOk={onSaveQulifica}
        confirmLoading={getQualifyByIdLoading || addQualifyLoading || editQualifyLoading}
      >
        <Spin spinning={getQualifyByIdLoading || addQualifyLoading || editQualifyLoading}>
          <div className={pageStyles['fromView-styles']}>
            <Form form={qulificationForm}>
              <Row>
                <Col span={24}>
                  <Form.Item label="资质类型" name="attachType" rules={[{ required: true, message: '请选择资质类型' }]}>
                    <Select placeholder="请选择资质类型" loading={mapLoading}>
                      {loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.QUALIFICA_TYPE}`]?.map((item: any) => {
                        return (
                          <Select.Option key={item?.id} value={item?.id}>
                            {item?.name}
                          </Select.Option>
                        );
                      })}
                    </Select>
                  </Form.Item>
                </Col>
                <UploadFormCommon
                  form={qulificationForm}
                  fileFormName={'attachURL'}
                  spanCol={24}
                  inRowProportion={24}
                  name={'attachFile'}
                  label="资质文件"
                  required={true}
                  accept={'.jpg|.png|.jpeg'}
                  url={'/supplierInfoController/uploadFile'}
                  downloadUrl={'/supplierInfoController/downloadFile'}
                  fileFormDelName={'attachURLDel'}
                  delFunc={() => {}}
                  maxFile={1}
                  fieldBusiPath={'supplier/info'}
                  defaultFiles={qualifiCheckRows?.id ? qualifiCheckRows?.attachURL || null : null}
                  // defaultFiles={qualifiCheckRows && JSON.stringify(qualifiCheckRows) != '{}' ? qualifiCheckRows?.attachURL : null}
                  //defaultFiles={null} //模拟数据-王志龙
                >
                  资质文件
                </UploadFormCommon>
                <TagSelectNew
                  colSpan={24}
                  formLabel="是否永久有效"
                  formName="isExpire"
                  defalultKeys={qualifiCheckRows?.isExpire == undefined ? 1 : qualifiCheckRows?.isExpire}
                  radioList={[
                    {
                      value: 1,
                      name: '是',
                    },
                    {
                      value: 0,
                      name: '否',
                    },
                  ]}
                  onChange={(checkValue: number) => {
                    setIsExpireEndTime(checkValue);
                  }}
                />
                {isExpireEndTime == 0 && (
                  <>
                    <Col span={24}>
                      <Form.Item label="开始时间" name="expireBegin" rules={[{ required: true, message: '请选择开始时间' }]}>
                        <TodayDatePicker
                          allowClear={true}
                          placeholder="请选择开始时间"
                          style={{ width: '100%' }}
                          format={'YYYY-MM-DD'}
                          disabledDate={(current: any) => {
                            return current && current > moment();
                          }}
                        />
                      </Form.Item>
                    </Col>
                    <Col span={24}>
                      <Form.Item
                        label="结束时间"
                        name="expireFinish"
                        rules={[
                          {
                            required: true,
                            message: '请选择结束时间',
                          },
                        ]}
                      >
                        <TodayDatePicker
                          allowClear={true}
                          placeholder="请选择结束时间"
                          style={{ width: '100%' }}
                          format={'YYYY-MM-DD'}
                          disabledDate={(current: any) => {
                            return current && current < qulificationForm?.getFieldValue('expireBegin');
                          }}
                        />
                      </Form.Item>
                    </Col>
                  </>
                )}

                <Col span={24}>
                  <Form.Item label="资质描述" name="attachContent">
                    <Input.TextArea placeholder={`请输入资质描述`} showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
